﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TPOJ.Model;
using TPOJ.Core;
using System.IO;

namespace TPOJ.BLL
{
    public static class JudgeBOAsynchronous
    {
        private static readonly TPOJ.IMessaging.IQueueMessage asynchMessage = TPOJ.MessagingFactory.QueueAccess.CreateMessage();

        public static void Submit(Message message)
        {
            asynchMessage.Send(message);
        }

        public static void Judge(int problemId, string language, string code, int userId, string sourcePath, string testsPath, string outputPath, int? contestId, DateTime submitTime)
        {
            SolutionBO solutionBO = new SolutionBO();
            Solution solution = solutionBO.AddSolution(problemId, language, code, userId, contestId, submitTime);

            if (contestId != null)
            {
                int cellId = Utils.GetContestProblemLabel(contestId.Value, problemId);
                Utils.UpdateStanding(contestId.Value, userId, cellId, submitTime, ResultType.Pending, 1);
            }

            sourcePath += solution.UniqueID + ".code";
            
            MakeTempFile(solution.Code, sourcePath);

            Message message = new Message();
            message.ProblemId = problemId;
            message.SolutionId = solution.UniqueID;
            message.Language = language;
            message.Code = code;
            message.TimeLimit = solution.Problem.TimeLimit;
            message.MemoryLimit = solution.Problem.MemoryLimit;

            JudgeBOAsynchronous.Submit(message);
        }

        private static void MakeTempFile(string code, string path)
        {
            using (var file = File.CreateText(path))
            {
                file.Write(code);
            }
        }

    }
}
